<template>
  <div id="system-backup" class="relative">
    <page-loading></page-loading>
    <div class="form-wrap mb20">
      <div v-for="(item, idx) in data.fields" :key="idx">
        <os-entry :item='item' v-if="item.type=='entry'">
          <div class="btn btn-blue" @click="handleClick(idx)" :title="idx==0 ? $t('hoverTitle.downloadFile'):''">{{item.btn}}</div>
        </os-entry>
        <os-input :item="item" v-model="fileName" v-if="item.type=='input'"
        width="300px" @operate="$refs.upload.click()">
        </os-input>
        <!-- <os-select :item='item' v-model="save_upgrade" whole-field="true"
        :options="options" v-if="item.type=='switch'">
        </os-select> -->
      </div>
      <input type="file" ref="upload" @change="handleChange" style="width: 0; height: 0;"/>
    </div>
    <div class="toolbar">{{data.toolbar}}</div>
    <a name="file" :href="assetsUrl" mce_href="#" download="backup.tar.gz" ref="downloadApi" style="display:none"></a>
    <os-modal :loading="showModal" :notification="notification"></os-modal>
  </div>
</template>

<script>
import { mapState } from 'vuex'

  export default {
    data(){
      return {
        assetsUrl: "/backup.tar.gz",
        fileName: "",
        file: null,
        save_upgrade: "0",
        options: this.$t('system.update.save_select'),
        showModal: false,
        notification: "",
      }
    },
    computed: {
      data(){
        return this.$t('system.backup')
      },
      ...mapState({
        durationLong: state => state.info.durationLong,
        durationReset: state => state.info.durationReset,
      })
    },
    methods: {
      handleClick(idx){
        if(idx==0) {
          this.proxy_req("get", "/webapi?op=sysupgrade_backup", false, res=> {
            this.assetsUrl = res.backup_path
            // this.assetsUrl = "http://192.168.10.156/backup.tar.gz"
            console.log(this.assetsUrl, res.backup_path)
            this.$refs.downloadApi.click()
          }, true, )
        } else {
          this.$confirm(this.$t("notification.confirmReset"), {
            type: "warning",
            title: this.$t("messageBox.title.info"),
          }).then(res=> {
            this.longLoading("get", "/webapi?op=reset", null, ()=> {

            },"showModal", "notification", this.$t("notification.resetLoading"), 
            this.$t("notification.resetSuccess"), this.durationReset )
          }).catch(err=> {})
        }
      },
      handleChange(e){
        // method: post  multiple: multiple  enctype: multipart/form-data
        // FormData FileReader
        console.log(e.target.files)
        let file = e.target.files[0]
        this.fileName = file.name
        let formData = new FormData()
        formData.append('firmware', file)
        this.file = formData
        // let URL = window.URL || window.wenkitURL
        // console.log(URL.createObjectURL(e.target.files[0]))
        let reader = new FileReader()
        reader.onload = e=> {
          console.log(e.target.result)
        }
        reader.readAsDataURL(file)
        this.handle_update()
        // FormData.(get getAll keys)
        // 用同一个字段append多个值
        // console.log(formData.getAll('file'), formData.get('file'), formData.keys())
        // const config = {
        //   headers: { "Content-Type": "multipart/form-data" }
        // };
        // this.axios.post("/.../uploadTest", param, config).then(res => {
        //   console.log(res);
        // });
        // 获取 window 的 URL 工具
        // var URL = window.URL || window.webkitURL;
        // 通过 file 生成目标 url  并不是本地文件系统的路径
        // var imgURL = URL.createObjectURL(file);
        // 用这个 URL 产生一个 <img> 将其显示出来
        // $('.fbpj .container').prev().find("img").attr('src', imgURL);
        // 使用下面这句可以在内存中释放对此 url 的伺服，跑了之后那个 URL 就无效了
           //URL.revokeObjectURL(imgURL);
      },
      handle_update(){
        if(this.file == null){
          this.$message({
            type: "warning",
            message: this.$t("notification.lackFile"),
            showClose: true,
          })
          return
        }
        const loading = this.createLoading()
        // this.$req.post('/webapi?op=sysupgrade_execute').then(res=> {
        //   if(res.code == '1'){
        //     loading.close()
        //     this.$message({
        //       type: 'success',
        //       message: 'upgrade success',
        //     })
        //   } else {
        //     loading.close()
        //     this.$message({
        //       type: 'danger',
        //       message: 'upgrade failed',
        //     })
        //   }
        // }).finally(()=> {
        //   loading.close()
        // })

        // 每一个Promise都应该在finally里面将异常处理掉
        // "$FORM_AC_TOKEN"
        this.$req.post('/webapi?op=sysupgrade_backup_upload', this.file).then(res=> {
          if(res.code && res.code=="1"){
            console.log("ok")
            this.longLoading("post", "/webapi?op=sysupgrade_backup_execute", 
            {save_upgrade: this.save_upgrade}, res=> {
              // this.goLogin()
            }, "showModal", "notification", this.$t('notification.sysbackupLoading'), 
            this.$t("notification.operateSuccess"), this.durationLong, loading)
            // this.$req.post('/webapi?op=sysupgrade_backup_execute', {
            // save_upgrade: this.save_upgrade}).then(res=> {
            //   if(res.code == '1'){
            //     loading.close()
            //     this.showModal = true
            //     setTimeout(()=> {
            //       this.showModal = false
            //       this.$message({
            //         type: 'success',
            //         message: this.$t("notification.operateSuccess"),
            //       })
            //     }, this.durationLong)
            //   } else {
            //     loading.close()
            //     this.$message({
            //       type: 'error',
            //       message: this.$t("notification.lackUpgradeFireware"),
            //     })
            //   }
            // }).finally(()=> {
            //   loading.close()
            // })
          } else if(res.code == "-4") {
            loading.close()
            this.$message({
              type: 'error',
              message: this.$t("notification.invilidFileType"),
              showClose: true,
            })
          } else if( res.code == "-6"){
            loading.close()
            this.$message({
              type: 'error',
              message: this.$t("notification.uploadFileFailed"),
              showClose: true,
            })
          }
        }).catch(res=> {
          if(res.code == "-4") {
            loading.close()
            this.$message({
              type: 'error',
              message: this.$t("notification.invalidFileType"),
              showClose: true,
            })
          } else if( res.code == "-6"){
            loading.close()
            this.$message({
              type: 'error',
              message: this.$t("notification.uploadFileFailed"),
              showClose: true,
            })
          }
        }).finally(()=> {
          loading? loading.close() : ""
        })
        // this.proxy_req('post', '/webapi?op=sysupgrade_upload_file', this.file, res=> {
        //   if(res.code=="1"){

        //   } else {
        //     this.$message({
        //       type: 'danger',
        //       message: 'file upload failed',
        //     })
        //   }
        // }, true)
      },
    },
    created(){
      this.$bus.emit('changeTab', 1)
    }
  }
</script>

<style lang="scss" scoped>
  .divide-line{
    height: 2px;
    background-color: #cccccc;
  }
</style>
